package com.czx.factory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.czx.entity.Handler;
import com.czx.handler.AbstractHandler;
import com.czx.mapper.HandlerMapper;
import com.czx.util.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class HandlerFactory {

    @Autowired
    private HandlerMapper handlerMapper;

    public AbstractHandler getHandler(Handler handler) {
        AbstractHandler backHandler;
        LambdaQueryWrapper<Handler> wrappers;
        if (handler == null) {
            wrappers = Wrappers.<Handler>lambdaQuery().isNull(Handler::getPreBeanId);
            Handler preHandler = handlerMapper.selectOne(wrappers);
            backHandler = SpringUtils.getBean(preHandler.getBeanId(), AbstractHandler.class);
            if (!StringUtils.isEmpty(preHandler.getNextBeanId())) {
                backHandler.setNext(getHandler(preHandler));
            }
        } else {
            wrappers = Wrappers.<Handler>lambdaQuery().eq(Handler::getBeanId, handler.getNextBeanId());
            Handler nextHandler = handlerMapper.selectOne(wrappers);
            backHandler = SpringUtils.getBean(nextHandler.getBeanId(), AbstractHandler.class);
            if (!StringUtils.isEmpty(nextHandler.getNextBeanId())) {
                backHandler.setNext(getHandler(nextHandler));
            }
        }
        return backHandler;
    }
}
